import tushare as ts
import time
import numpy as np

# 初始化股票列表
from ZIndex.tool import Util

stock_list = ['300222.SZ', '002623.SZ', '000788.SZ', '002031.SZ', '300456.SZ', '300933.SZ', '000012.SZ']

# 初始化tushare连接
ts.set_token('6557f39ddf25c764e5124721450abfd1981f5ff98274f68caf9acd9f')
pro = ts.pro_api()
stock_info_file = 'stock_info.csv'
trade_info_file = 'trade_info.csv'

for i in stock_list:
    print(i)
    # 返回DataFrame
    # 获取上市公司基本信息 每分钟最多访问该接口5次
    stock_info = pro.stock_company(ts_code=i, fields='ts_code,chairman,manager,secretary,reg_capital,setup_date,province,employees,main_business,business_scope')
    print(stock_info)
    Util.dataFrameToCsv(stock_info, stock_info_file, True)
    time.sleep(15)

    trade_info = pro.daily(ts_code=i, start_date='20190101', end_date='20220101')
    Util.dataFrameToCsv(trade_info, trade_info_file, False)
    # 计算股价对数收益率
    trade_info['log_ret'] = np.log(trade_info['close']/trade_info['close'].shift(1))
    # 计算股价月度波动率
    trade_info['volatility'] = trade_info['log_ret'].rolling(window=22, center=False).std()*np.sqrt(22)

    # print(trade_info['volatility'])
    trade_info[['close', 'volatility']].plot(subplots=True, color='blue', figsize=(10,8))






